package com.example.idgrenternate.util;


import org.apache.commons.codec.digest.DigestUtils;

public class IdGrenateUtils {
    //26+26+10 62位
    final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
            'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

    /**
     * 长连接URL转换未4个短KEY
     */
    public static String[] shortUrl(String url){
        String key="";
        //对地址进行md5
        String sMD5EncryptResult= DigestUtils.md5Hex(key+url);

        String hex=sMD5EncryptResult;
        String [] resUrl=new String[4];
        for (int i=0;i<4;i++){
            //取出8位字符串，md5 32位，被切割为4组，每组8个字符
            String stempSubString=hex.substring(i*8,i*8+8);
            //先转换位16进制，然后用0x3FFFFFFF进行位与运算，目的是格式化截取前30位
            Long LHexLong=0x3FFFFFFF&Long.parseLong(stempSubString,16);
            String outChars="";
            for (int j=0;j<6;j++){
                //0x0000003D 它的10进制是61
                long index=0x0000003D&LHexLong;
                outChars+=digits[(int)index];
                LHexLong=LHexLong>>5;
            }
            resUrl[i]=outChars;
        }
        return resUrl;
    }

    public static void main(String[] args) {
        //长链接
        String longUrl="https://detail.tmall.com/item.htm?id=597254411409";
        //转换为短链接后6位码
        String[] shortCodeArray=shortUrl(longUrl);
        for (int i=0;i<shortCodeArray.length;i++){
            System.out.println(shortCodeArray[i]);
        }
    }
}
